package com.aruba.attendance.ui.widget.loading

import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.tween
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Workspaces
import androidx.compose.material3.Icon
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.graphics.vector.ImageVector
import com.aruba.attendance.ui.widget.loading.enums.LoadingState
import kotlinx.coroutines.delay

/**
 * 带旋转动画效果的加载中组件
 * Created by aruba on 2023/2/14.
 */
@Composable
fun LoadingContent(
    loadingState: State<LoadingState>,
    defaultContent: @Composable (() -> Unit)? = null,
    loadingImageVector: ImageVector = Icons.Default.Workspaces,
    completeImageVector: ImageVector = Icons.Default.Check,
    animFinishCallback: (() -> Unit)? = null,
) {
    when (loadingState.value) {
        LoadingState.Loading -> {
            var targetValue by remember { mutableStateOf(0f) }
            val animateRotateVal by animateFloatAsState(
                targetValue,
                animationSpec = infiniteRepeatable(
                    animation = tween(1500, easing = LinearEasing)
                )
            )
            LaunchedEffect(Unit) {
                targetValue = 360f
            }
            Icon(
                loadingImageVector, contentDescription = "loadingImageVector",
                modifier = Modifier.rotate(animateRotateVal)
            )
        }
        LoadingState.Complete -> {
            Icon(completeImageVector, contentDescription = "completeImageVector")
            LaunchedEffect(Unit) {
                delay(200)
                animFinishCallback?.invoke()
            }
        }
        else -> {
            defaultContent?.invoke()
        }
    }
}